package org.bdware.irs;

import com.google.gson.Gson;
import org.apache.log4j.Logger;

import java.io.*;

public class IrsConfig {

    static Logger logger = Logger.getLogger(IrsConfig.class);
    public String irsAddress;
    public int port;
    public int tcpPort;
    public String prefix;
    public String jwk;
    public boolean grsEnabled;
    public String grsAddress;


    public static IrsConfig loadFromConfigFile(String filePath) {
        logger.info("try to load config from: " + filePath);
        try {
            String configJson = readFile(filePath);
            return new Gson().fromJson(configJson, IrsConfig.class);
        } catch (Exception e) {
            return null;
        }
    }

    private static String readFile(String path) throws Exception {
        File file = new File(path);
        logger.debug("conf file absolute path: " + file.getAbsolutePath());
        StringBuilder configJson = new StringBuilder();
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line = br.readLine();
        while (line != null) {
            configJson.append(line);
            line = br.readLine();
        }
        br.close();
        return configJson.toString();
    }

    public void save(String filePath) throws IOException {
        File f = new File(filePath);
        logger.info("config file path: " + f.getAbsolutePath());
        FileWriter fw = new FileWriter(f);
        fw.write(new Gson().toJson(this));
        fw.flush();
    }

    public static IrsConfig createDefaultConfig() {

        /**
         * Default irs Service Information
         */
        String irsAddress = "http://127.0.0.1:10001/";
        int port = 10001;
        int tcpPort = 2641;
        String prefix = "86.5000.470";
        String jwk = "{}";

        IrsConfig irsConfig = new IrsConfig();

        irsConfig.irsAddress = irsAddress;
        irsConfig.port = port;
        irsConfig.tcpPort = tcpPort;
        irsConfig.jwk = jwk;
        irsConfig.prefix = prefix;

        return irsConfig;
    }

}
